package com.xckj.cycling.context

import android.app.Application
import android.content.pm.PackageManager
import android.util.Base64
import android.util.Log
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import com.mapbox.navigation.base.options.NavigationOptions
import com.mapbox.navigation.core.lifecycle.MapboxNavigationApp
import com.tencent.bugly.crashreport.CrashReport
import com.xckj.cycling.BuildConfig
import com.xckj.cycling.R
import com.xckj.cycling.utils.LanguageUtils
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException


class AppContext : Application(), ViewModelStoreOwner {

    val options by lazy {
        NavigationOptions.Builder(this)
            .accessToken(getString(R.string.mapbox_access_token))
            // additional options
            .build()
    }

    fun updateLanguage() {
        val local = LanguageUtils.getLocal()
        local?.let {
            resources.configuration.setLocales(it)
        }
    }

    override fun onCreate() {
        _context = this
        super.onCreate()
//        CrashReport.initCrashReport(this, "828a6ec2a0", BuildConfig.DEBUG)
        CrashReport.initCrashReport(this, "eb7b3f86e7", BuildConfig.DEBUG)
        MapboxNavigationApp.setup {
            options
        }
        printKeyHash()
        updateLanguage()
    }

    private fun printKeyHash() {
        // Add code to print out the key hash
        try {
            val info =
                packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES)
            for (signature in info.signatures) {
                val md: MessageDigest = MessageDigest.getInstance("SHA")
                md.update(signature.toByteArray())
                Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT))
            }
        } catch (e: PackageManager.NameNotFoundException) {
            Log.e("KeyHash:", e.toString())
        } catch (e: NoSuchAlgorithmException) {
            Log.e("KeyHash:", e.toString())
        }
    }

    companion object {
        private var _context: AppContext? = null

        @JvmStatic
        fun globalContext(): AppContext {
            return _context!!
        }
    }

    var modelStore: ViewModelStore? = null
    override fun getViewModelStore(): ViewModelStore {
        if (modelStore == null) {
            modelStore = ViewModelStore()
        }
        return modelStore!!
    }
}


